package com.zheinfo.biz.service.impl;

import com.zheinfo.biz.domain.UserAddress;
import com.zheinfo.biz.mapper.UserAddressMapper;
import com.zheinfo.biz.service.IUserAddressService;
import com.zheinfo.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户收货地址Service业务层处理
 * 
 * @author zheinfo
 */
@Service
public class UserAddressServiceImpl implements IUserAddressService 
{
    @Autowired
    private UserAddressMapper userAddressMapper;

    /**
     * 查询用户收货地址
     * 
     * @param id 用户收货地址主键ID
     * @return 用户收货地址
     */
    @Override
    public UserAddress selectUserAddressById(Long id)
    {
        return userAddressMapper.selectUserAddressById(id);
    }

    /**
     * 查询用户收货地址列表
     * 
     * @param userAddress 用户收货地址
     * @return 用户收货地址
     */
    @Override
    public List<UserAddress> selectUserAddressList(UserAddress userAddress)
    {
        return userAddressMapper.selectUserAddressList(userAddress);
    }

    /**
     * 新增用户收货地址
     * 
     * @param userAddress 用户收货地址
     * @return 结果
     */
    @Override
    public int insertUserAddress(UserAddress userAddress)
    {
        // 如果设置为默认地址，先将该用户的所有地址设为非默认
        if (userAddress.getIsDefault() != null && userAddress.getIsDefault() == 1) {
            userAddressMapper.updateAllAddressNotDefault(userAddress.getUserId());
        }
        userAddress.setCreateTime(DateUtils.getNowDate());
        return userAddressMapper.insertUserAddress(userAddress);
    }

    /**
     * 修改用户收货地址
     * 
     * @param userAddress 用户收货地址
     * @return 结果
     */
    @Override
    public int updateUserAddress(UserAddress userAddress)
    {
        // 如果设置为默认地址，先将该用户的所有地址设为非默认
        if (userAddress.getIsDefault() != null && userAddress.getIsDefault() == 1) {
            // 需要获取userId，如果传入的userAddress没有userId，从数据库查询
            Long userId = userAddress.getUserId();
            if (userId == null) {
                UserAddress existAddress = userAddressMapper.selectUserAddressById(userAddress.getId());
                if (existAddress != null) {
                    userId = existAddress.getUserId();
                }
            }
            if (userId != null) {
                userAddressMapper.updateAllAddressNotDefault(userId);
            }
        }
        userAddress.setUpdateTime(DateUtils.getNowDate());
        return userAddressMapper.updateUserAddress(userAddress);
    }

    /**
     * 批量删除用户收货地址
     * 
     * @param ids 需要删除的用户收货地址主键ID
     * @return 结果
     */
    @Override
    public int deleteUserAddressByIds(Long[] ids)
    {
        return userAddressMapper.deleteUserAddressByIds(ids);
    }

    /**
     * 删除用户收货地址信息
     * 
     * @param id 用户收货地址主键ID
     * @return 结果
     */
    @Override
    public int deleteUserAddressById(Long id)
    {
        return userAddressMapper.deleteUserAddressById(id);
    }
}